'''
Created on Jan 24, 2011

@author: oabalbin
'''
import logging
import os
import sys
import subprocess
import tempfile

from optparse import OptionParser
from exome.jobs.base import JOB_SUCCESS, JOB_ERROR
from exome.jobs.job_runner import qsub_cac,qsub_loc, run_local
from exome.jobs.config import ExomePipelineConfig, ExomeAnalysisConfig, ExomeLaneConfig
from exome.gatk_cluster.samtools_commands_cluster import samtools_view, index_bam_file
from exome.gatk_cluster.picard_commands_cluster import sortIndexSam

# Global Variables
NODE_MEM=45000.0
NODE_CORES=12
SINGLE_CORE=1
MEM_PER_CORE= int(float(NODE_MEM) / NODE_CORES)
# wt=walltime
WT_SHORT= "24:00:00"
WT_LONG= "60:00:00" 


def read_extractor(analysis, config, output_folder, jobrunfunc):
    '''
    '''
    my_email=config.email_addresses
    path_to_sam=config.samtools_path
    picard_path = config.picard_path
    # region could be a string from other function
    
    region='chr5:45,259,353-45,696,220 chr5:118,407,084-118,584,822 chr6:51,480,145-51,952,423'+\
           ' chr6:26124412-26139311 chr8 chr10:89,623,195-89,728,531 chr11:64,570,996-64,578,188'+\
           ' chr11:108,093,559-108,239,826 chr14:38,059,193-38,064,489 chr17:7,571,720-7,590,863'
    
    for sample in analysis.samples:
        for lane in sample.lanes:
            
            lname = lane.name.split('_')
            jobn='re'+lname[1][:5]+'_'+lname[2]
            
            lane_file = os.path.join(sample.output_dir, lane.name + ".xml")
            analysis.lane_dir
            job = ExomeLaneConfig()
            job.from_xml(lane_file, analysis.lane_dir)
            
            # This must be changed to reflect config file.
            bam_output_file = os.path.join(output_folder,lane.name+'/align/aligned_reads.bam')
            bam_index_file = os.path.join(output_folder,lane.name+'/align/aligned_reads')
            
            args=samtools_view(job.align_bam_file,bam_output_file, 
                                path_to_sam, region)
            
            jobidtm = jobrunfunc(jobn+'_trim', args, SINGLE_CORE, cwd=None, walltime=WT_SHORT, 
                                 pmem=MEM_PER_CORE, deps=None, stdout=None, 
                                 email_addresses=my_email)
            
            args = sortIndexSam(bam_output_file, bam_index_file, use_mem=2048, picard_path=picard_path, 
                         sort_order='coordinate')
            args1=['mv',bam_index_file,bam_output_file]
            args1=",".join(args1).replace(',',' ')
            args = args+'\n'+args1

            jobidtm = jobrunfunc(jobn+'_ind', args, SINGLE_CORE, cwd=None, walltime=WT_SHORT, 
                                 pmem=MEM_PER_CORE, deps=jobidtm, stdout=None, 
                                 email_addresses=my_email)

    
if __name__ == '__main__':
        
    optionparser = OptionParser("usage: %prog [options] ")
    optionparser.add_option("-r", "--config_file", dest="config_file",
                            help="file with run configuration")
    optionparser.add_option("-a", "--analysis_file", dest="analysis_file",
                            help="file with experiment configuration")
    optionparser.add_option("-f", "--output_folder", dest="output_folder",
                            help="It stores the output root folder.")
    optionparser.add_option("--local", dest="local", action="store_true", default=False)
    optionparser.add_option("--cluster", dest="cluster", action="store_true", default=False)
    optionparser.add_option("-p", "--processes", type=int, dest="num_processors", default=1)

    (options, args) = optionparser.parse_args()    

    config = ExomePipelineConfig()
    config.from_xml(options.config_file)
    analysis = ExomeAnalysisConfig()
    analysis.from_xml(options.analysis_file, config.output_dir)


    if not (options.local ^ options.cluster):
        print "Must set either --local or --cluster to run job"
    if options.local:
        jobrunfunc = run_local
    elif options.cluster:
        jobrunfunc = qsub
        
    read_extractor(analysis, config, options.output_folder, jobrunfunc)
